package com.lorizz.model.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;

public abstract class AbstractRepository<ID extends Serializable> {

    private EntityManager entityManager;

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public <T> T persist(T entity) {
        entityManager.persist(entity);
        return entity;
    }

    public <T> void remove(T entity) {
        entityManager.remove(entity);
    }

    public CriteriaBuilder getCriteriaBuilder() {
        return entityManager.getCriteriaBuilder();
    }

    public <T> List<T> executeQuery(CriteriaQuery<? extends T> query) {
        List<T> result = new ArrayList<T>();
        for (T t : entityManager.createQuery(query).getResultList()) {
            result.add(t);
        }
        return result;
    }

    public <T> List<T> executeQuery(CriteriaQuery<? extends T> query,
            int first, int size) {
        TypedQuery<? extends T> q = entityManager.createQuery(query);
        if (first > -1)
            q.setFirstResult(first);
        if (size > 0)
            q.setMaxResults(size);
        List<T> result = new ArrayList<T>();
        for (T t : q.getResultList()) {
            result.add(t);
        }
        return result;
    }

}
